import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/common/app.dart';
import 'package:flutter_smart_heating/pages/plugins/qrcode/widget/button.dart';
import 'package:flutter_smart_heating/ui/src/permission.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:get/get.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import './handle.dart';
import 'widget/line.dart';

class QrcodePage extends StatefulWidget {
  const QrcodePage({super.key});

  @override
  State<QrcodePage> createState() => _QrcodePageState();
}

class _QrcodePageState extends State<QrcodePage> {
  MobileScannerController controller = MobileScannerController();

  ValueNotifier<bool> isReady = ValueNotifier<bool>(false);
  ValueNotifier<bool> showLoading = ValueNotifier<bool>(false);
  ValueNotifier<bool> scaning = ValueNotifier<bool>(false);
  ValueNotifier<bool> hasPermission = ValueNotifier<bool>(false);
  bool allReady = false;
  @override
  void dispose() {
    controller.stop();
    controller.dispose();
    super.dispose();
  }

  getPermission() async {
    hasPermission.value = await UiPeromission.check(
      context,
      title: "扫描二维码需要调用以下权限",
      permissions: [UiPermissionData('摄像机', Permission.camera)],
    );
    isReady.value = true;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      onPopInvoked: (val) {
        controller.stop();
      },
      child: Scaffold(
        extendBodyBehindAppBar: true,
        backgroundColor: Colors.black,
        appBar: AppBar(
          elevation: 0,
          leading: IconButton(
            onPressed: () {
              App.back(context);
            },
            icon: const CircleAvatar(
              radius: 13,
              backgroundColor: Colors.white70,
              child: Icon(
                Icons.close,
                size: 16,
                color: Colors.black87,
              ),
            ),
          ),
          backgroundColor: Colors.black.withOpacity(0),
          foregroundColor: Colors.white,
          title: const Text(
            "扫一扫",
            style: TextStyle(color: Colors.white, shadows: [
              Shadow(
                color: Colors.black,
                blurRadius: 6,
              )
            ]),
          ),
        ),
        body: UiLifeCycle(
          onRouteDone: () {
            getPermission();
          },
          child: AnimatedSwitcher(
            duration: kThemeAnimationDuration,
            child: ValueListenableBuilder(
              valueListenable: isReady,
              builder: (context, state, child) {
                return state ? scanView() : loadingView();
              },
            ),
          ),
        ),
        bottomNavigationBar: ValueListenableBuilder(
            valueListenable: hasPermission,
            builder: (context, state, widget) {
              return state
                  ? IntrinsicHeight(
                      child: SafeArea(
                        bottom: true,
                        minimum: const EdgeInsets.only(bottom: 20, top: 10),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: [
                            ValueListenableBuilder(
                              valueListenable: controller.torchState,
                              builder: (context, state, child) {
                                bool isFlashOn = state == TorchState.on;
                                return QrcodeButtonView(
                                  icon: isFlashOn
                                      ? UiIcons.flash_on
                                      : UiIcons.flash_off,
                                  text: isFlashOn ? '轻触关闭' : '轻触照亮',
                                  onTap: () {
                                    App.hapticFeedback();
                                    controller.toggleTorch();
                                  },
                                );
                              },
                            ),
                            QrcodeButtonView(
                              icon: UiIcons.image_scan,
                              text: '图片识别',
                              onTap: () async {
                                controller.stop();
                                scaning.value = false;
                                showLoading.value = true;
                                if (await QrcodeHandle.gallery(context)) {
                                  if (allReady) {
                                    scaning.value = true;
                                    controller.start();
                                  }

                                  showLoading.value = false;
                                }
                              },
                            )
                          ],
                        ),
                      ),
                    )
                  : const SizedBox.shrink();
            }),
      ),
    );
  }

  Widget scanView() {
    if (!hasPermission.value) {
      return Center(
        child: UiTap(
          onTap: () async {
            getPermission();
          },
          child: DefaultTextStyle(
            style: const TextStyle(color: Colors.white70),
            child: Container(
              padding: const EdgeInsets.all(20),
              decoration: BoxDecoration(
                color: Colors.grey.withOpacity(0.15),
                borderRadius: BorderRadius.circular(10),
              ),
              child: const Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(
                    Icons.camera_alt,
                    size: 40,
                    color: Colors.white,
                  ),
                  SizedBox(height: 10),
                  Text(
                    '扫码需要您打开摄像头权限',
                  ),
                ],
              ),
            ),
          ),
        ),
      );
    }
    return Stack(
      children: [
        MobileScanner(
          errorBuilder: (context, error, p2) {
            return Center(
              child: Container(
                padding: const EdgeInsets.all(20),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Text(
                  (error.errorDetails?.message ?? '出错啦 ').tr,
                  textAlign: TextAlign.center,
                  style: const TextStyle(color: Colors.white),
                ),
              ),
            );
          },
          onScannerStarted: (arguments) async {
            await 0.2.delay();
            scaning.value = true;
            allReady = true;
          },
          controller: controller,
          // fit: BoxFit.contain,
          onDetect: (capture) async {
            final List<Barcode> barcodes = capture.barcodes;
            for (final barcode in barcodes) {
              controller.stop();
              controller.dispose();
              scaning.value = false;
              await QrcodeHandle.resolve(barcode.rawValue.toString());
              Get.back();
            }
          },
        ),
        ValueListenableBuilder(
          valueListenable: scaning,
          builder: (context, state, child) {
            return state && isReady.value
                ? const QrcodeLineView()
                : Container();
          },
        ),
        ValueListenableBuilder(
          valueListenable: showLoading,
          builder: (context, state, child) {
            return Align(
              child: state ? loadingView() : Container(),
            );
          },
        ),
      ],
    );
  }

  Widget loadingView() {
    return const Center(
      child: CupertinoActivityIndicator(
        color: Colors.white,
      ),
    );
  }
}
